package com.example.springmvc.controller;

import com.example.springmvc.exception.ForbiddenException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

/**
 * 本文描述如何从spring mvc Controller中返回自定义状态码。
 * 需要特别说明的是技术上可以返回任意状态码，但错误的状态码可能引起逻辑上误解。一般使用(4XX 和 5XX)。
 */
@RestController
public class HttpStatusController {

    /**
     * 只响应状态码和数据
     * @return 响应
     */
    @RequestMapping(value = "/content", method = RequestMethod.GET)
    @ResponseBody
    @ResponseStatus(HttpStatus.BAD_GATEWAY)
    public Object sendContentAndStatusCode() {
        return "please view the status code.";
    }

    /**
     * 只响应状态码
     * @return 响应
     */
    @RequestMapping(value = "/controller", method = RequestMethod.GET)
    @ResponseBody
    public ResponseEntity sendViaResponseEntity() {
        return new ResponseEntity(HttpStatus.NOT_ACCEPTABLE);
    }

    /**
     * 抛出异常，响应状态码
     * @return 响应
     */
    @RequestMapping(value = "/exception", method = RequestMethod.GET)
    @ResponseBody
    public ResponseEntity sendViaException() {
        throw new ForbiddenException();
    }
}
